package com.droidlogic.FileBrower.GiecSmb;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Collections;
import java.util.List;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;

public class Utils {
	public static String ITEM_TYPE = "item_type";
	public static String ITEM_NAME = "item_name";
	public static String FILE_PATH = "file_path";
	public static String FILE_DATE = "file_date";
	public static String FILE_SIZE = "file_size";
	public static String ITEM_SIZE = "item_size";
	public static String ITEM_RW = "item_rw";
	
	public static String SMB_ROOT = "smb://";
	
	public static boolean hasNetwork(Context ctx) {
		ConnectivityManager connManager = (ConnectivityManager)ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo info = connManager.getActiveNetworkInfo();
		if(info==null) {
			LogUtils.e("Can not get ActiveNetworkInfo");
		} else {
			if(info.isConnected()) {
				LogUtils.e("Network is connected Type:" + info.getType());
				return true;
			} else {
				LogUtils.e("Network is disconnected Type:" + info.getType());
			}
		}
		return false;
	}

	/**
	 * Get IP address from first non-localhost interface
	 * @param ipv4  true=return ipv4, false=return ipv6
	 * @return  address or empty string
	 */
	public static String getIPAddress(boolean useIPv4) {
		try {
			List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
			for (NetworkInterface intf : interfaces) {
				List<InetAddress> addrs = Collections.list(intf.getInetAddresses());
				for (InetAddress addr : addrs) {
					if (!addr.isLoopbackAddress()) {
						String sAddr = addr.getHostAddress();
						//boolean isIPv4 = InetAddressUtils.isIPv4Address(sAddr);
						boolean isIPv4 = sAddr.indexOf(':')<0;

						if (useIPv4) {
							if (isIPv4)
								return sAddr;
						} else {
							if (!isIPv4) {
								int delim = sAddr.indexOf('%'); // drop ip6 zone suffix
								return delim<0 ? sAddr.toUpperCase() : sAddr.substring(0, delim).toUpperCase();
							}
						}
					}
				}
			}
		} catch (Exception ex) { } // for now eat exceptions
		return "";
	}
	

}
